// UserService.java
package com.community.service;

import com.community.dao.UserDao;
import com.community.dao.impl.UserDaoImpl;
import com.community.model.User;
import com.community.util.SecurityUtil;
import java.util.Optional;

public class UserService {
    private final UserDao userDao = new UserDaoImpl();

    public void registerUser(User user) {
        validateUser(user);
        if (userDao.getByUsername(user.getUsername()).isPresent()) {
            throw new IllegalArgumentException("用户名已存在");
        }
        user.setPassword(SecurityUtil.encrypt(user.getPassword()));
        userDao.insert(user);
    }

    public Optional<User> authenticate(String username, String password) {
        Optional<User> user = userDao.getByUsername(username);
        if (user.isPresent() && SecurityUtil.verify(password, user.get().getPassword())) {
            return user;
        }
        return Optional.empty();
    }

    private void validateUser(User user) {
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        if (user.getPassword() == null || user.getPassword().trim().length() < 6) {
            throw new IllegalArgumentException("密码至少需要6位");
        }
        if (user.getRole() == null || (!user.getRole().equals("ADMIN") && !user.getRole().equals("USER"))) {
            throw new IllegalArgumentException("无效的用户角色");
        }
    }

    public User login(String username, String password) {
        return userDao.getByUsername(username)
                .filter(user -> SecurityUtil.verify(password, user.getPassword()))
                .orElseThrow(() -> new IllegalArgumentException("用户名或密码错误"));
    }
}